<?php
namespace Data;

use Data\Drive\DataCache;
use Data\Drive\SetArrayKey;
use Data\Drive\ToQuerySql;
use PDO;

class Cache extends \Data
{
    public static function Run($conf)
    {
        if (!is_array($conf)) {
            self::Error("缓存查询参数必须为数组格式", __FILE__, __LINE__);
        }
        if (isset($conf['file'])) {
            $conf['file'] = DATA_CACHE_DIR . DS . $conf['file'];
        } else {
            $conf['file'] = self::getCacheFile($conf);
        }
        if (file_exists($conf['file'])) {
            return include $conf['file'];
        }
        $sql  = isset($conf['sql']) ? $conf['sql'] : ToQuerySql::Run($conf);
        $data = self::$db->query($sql);
        $code = self::$db->errorCode();
        if ($code != 00000) {
            $info = self::$db->errorInfo();
            self::Error(json_encode($info) . "\r\n" . $sql, __FILE__, __LINE__);
        } else if (!$data || $data->rowCount() == 0) {
            return null;
        }
        $data                           = $data->fetchAll(PDO::FETCH_ASSOC);
        $data                           = isset($conf['key']) ? SetArrayKey::Run($data, $conf['key']) : $data;
        isset($conf['format']) && $data = $conf['format']($data);
        DataCache::setCache($conf['file'], $data);
        return $data;
    }

    public static function getCacheFile($conf)
    {
        $table = preg_replace("/\s.+$/", "", $conf['table']);
        foreach ($conf as $key => $value) {
            if (is_array($value)) {
                $conf[$key] = serialize($value);
            }
        }
        $dataName = md5(implode(",", $conf));
        return DATA_CACHE_DIR . DS . $table . DS . $dataName . ".cache";
    }
}
